<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <title>IoT平台 - 管理员面板</title>
  <link rel="stylesheet" href="css/styles.css" />
</head>
<body>
  <div class="container">
    <h1>IoT平台管理员面板</h1>
    
    <!-- 管理员导航栏 -->
    <div class="navbar">
      <ul>
          <li><a href="#" class="nav-link active" data-page="admin-dashboard">管理员面板</a></li>
          <li><a href="#" class="nav-link" data-page="create-user-page">创建用户</a></li>
          <li><a href="#" class="nav-link" data-page="search-users-page">搜索用户</a></li>
          <li><a href="#" class="nav-link" data-page="logs-query-page">日志查询</a></li>
        </ul>
      <div class="user-info">
        <span>管理员: <span id="admin-name"></span> (<span id="admin-role"></span>)</span>
        <button class="logout-btn" onclick="clearToken(); window.location.href='login.html';">退出登录</button>
      </div>
    </div>
    
    <!-- 管理员仪表板 -->
    <div id="admin-dashboard" class="page">
      <div class="card">
        <div class="card-header">
          <h2 class="card-title">我的信息</h2>
        </div>
        <button onclick="onMe()">刷新用户信息</button>
        <pre id="meResultAdmin"></pre>
      </div>
      
      <div class="card">
        <div class="card-header">
          <h2 class="card-title">删除用户</h2>
        </div>
        <form onsubmit="onDelete(event)">
          <div class="form-group">
            <label>用户ID</label>
            <input name="userId" placeholder="例如: user123" required />
          </div>
          <button type="submit" class="danger">删除用户</button>
        </form>
        <pre id="deleteResult"></pre>
      </div>
    </div>
    
    <!-- 创建用户页面 -->
    <div id="create-user-page" class="page hidden">
      <div class="card">
        <div class="card-header">
          <h2 class="card-title">创建用户</h2>
        </div>
        <form onsubmit="onCreateUser(event)">
          <div class="form-group">
            <label>用户名 *</label>
            <input name="username" required autocomplete="username" />
          </div>
          <div class="form-group">
            <label>密码 *</label>
            <input name="password" type="password" required autocomplete="new-password" />
          </div>
          <div class="form-group">
            <label>邮箱</label>
            <input name="email" type="email" autocomplete="email" />
          </div>
          <div class="form-group">
            <label>手机号</label>
            <input name="phone" autocomplete="tel" />
          </div>
          <div class="form-group">
            <label>姓名</label>
            <input name="name" autocomplete="name" />
          </div>
          <div class="form-group">
            <label>身份证</label>
            <input name="idCard" />
          </div>
          <div class="form-group">
            <label>角色</label>
            <select name="role">
              <option value="USER">USER - 普通用户</option>
              <option value="ADMIN">ADMIN - 管理员</option>
            </select>
          </div>
          <div class="form-group">
            <label>状态</label>
            <select name="status">
              <option value="NORMAL">NORMAL - 正常</option>
              <option value="DISABLED">DISABLED - 禁用</option>
            </select>
          </div>
          <div class="form-group">
            <label>创建人</label>
            <input name="creator" />
          </div>
          <div class="form-group">
            <label>更新人</label>
            <input name="modifier" />
          </div>
          <div class="form-group">
            <label>备注</label>
            <input name="remark" />
          </div>
          <button type="submit">创建用户</button>
        </form>
        <pre id="createUserResult"></pre>
      </div>
    </div>
    
    <!-- 搜索用户页面 -->
    <div id="search-users-page" class="page hidden">
      <div class="card">
        <div class="card-header">
          <h2 class="card-title">搜索用户</h2>
        </div>
        <form onsubmit="onSearchUsers(event)">
          <div class="form-row">
            <div>
              <label>关键词(用户名/手机号/邮箱)</label>
              <input name="keyword" placeholder="搜索关键词" />
            </div>
            <div>
              <label>角色过滤</label>
              <select name="role">
                <option value="">全部角色</option>
                <option value="ADMIN">ADMIN</option>
                <option value="USER">USER</option>
              </select>
            </div>
            <div>
              <label>状态过滤</label>
              <select name="status">
                <option value="">全部状态</option>
                <option value="NORMAL">NORMAL</option>
                <option value="DISABLED">DISABLED</option>
              </select>
            </div>
          </div>
          <div class="form-row">
            <div>
              <label>页码</label>
              <input name="page" type="number" value="1" min="1" />
            </div>
            <div>
              <label>每页条数</label>
              <input name="size" type="number" value="10" min="1" max="100" />
            </div>
          </div>
          <button type="submit">搜索用户</button>
        </form>
        <pre id="searchUsersResult"></pre>
        <div class="user-list" id="searchUsersList"></div>
      </div>
      
      <!-- 编辑用户模态框 -->
      <div id="editUserModal" class="modal hidden">
        <div class="modal-content">
          <div class="modal-header">
            <h2>编辑用户信息</h2>
            <span class="close" onclick="closeEditUserModal()">&times;</span>
          </div>
          <div class="modal-body">
            <form id="editUserForm" onsubmit="onEditUserFromModal(event)">
              <div class="form-group">
                <label>用户名</label>
                <input id="editUsername" name="username" autocomplete="username" />
              </div>
              <div class="form-group">
                <label>邮箱</label>
                <input id="editEmail" name="email" type="email" autocomplete="email" />
              </div>
              <div class="form-group">
                <label>手机号</label>
                <input id="editPhone" name="phone" autocomplete="tel" />
              </div>
              <div class="form-group">
                <label>姓名</label>
                <input id="editName" name="name" autocomplete="name" />
              </div>
              <div class="form-group">
                <label>身份证</label>
                <input id="editIdCard" name="idCard" />
              </div>
              <div class="form-group">
                <label>角色</label>
                <select id="editRole" name="role">
                  <option value="USER">USER - 普通用户</option>
                  <option value="ADMIN">ADMIN - 管理员</option>
                </select>
              </div>
              <div class="form-group">
                <label>状态</label>
                <select id="editStatus" name="status">
                  <option value="NORMAL">NORMAL - 正常</option>
                  <option value="DISABLED">DISABLED - 禁用</option>
                </select>
              </div>
              <div class="form-group">
                <label>备注</label>
                <input id="editRemark" name="remark" />
              </div>
              <!-- 只读字段 -->
              <div class="form-group">
                <label>用户ID</label>
                <input id="editUserIdDisplay" disabled />
                <input type="hidden" id="editUserId" name="userId" />
              </div>
              <div class="form-group">
                <label>最后登录时间</label>
                <input id="editLastLoginTime" disabled />
              </div>
              <div class="form-group">
                <label>创建人</label>
                <input id="editCreator" disabled />
              </div>
              <div class="form-group">
                <label>编辑人</label>
                <input id="editModifier" disabled />
                <input type="hidden" id="editModifierHidden" name="modifier" />
              </div>
              <div class="form-actions">
                <button type="submit">更新用户信息</button>
                <button type="button" class="secondary" onclick="closeEditUserModal()">取消</button>
              </div>
            </form>
          </div>
        </div>
      </div>
      
      <!-- 重置密码模态框 -->
      <div id="resetPasswordModal" class="modal hidden">
        <div class="modal-content">
          <div class="modal-header">
            <h2>重置用户密码</h2>
            <span class="close" onclick="closeResetPasswordModal()">&times;</span>
          </div>
          <div class="modal-body">
            <form id="resetPasswordForm" onsubmit="onResetPasswordFromModal(event)">
              <input type="hidden" id="resetUserId" name="userId" />
              <div class="form-group">
                <label>用户名: <span id="resetUsername"></span></label>
              </div>
              <div class="form-group">
                <label>新密码 *</label>
                <input id="resetNewPassword" name="newPassword" type="password" required autocomplete="new-password" />
              </div>
              <div class="form-actions">
                <button type="submit">重置密码</button>
                <button type="button" class="secondary" onclick="closeResetPasswordModal()">取消</button>
              </div>
            </form>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 日志查询页面 -->
    <div id="logs-query-page" class="page hidden">
      <!-- 查询表单 -->
      <div class="card">
        <div class="card-header">
          <h2 class="card-title">日志查询条件</h2>
        </div>
        <form id="logQueryForm" onsubmit="onQueryLogs(event)">
          <div class="form-row">
            <div class="form-group">
              <label>开始时间</label>
              <input type="datetime-local" id="startTime" name="startTime">
            </div>
            <div class="form-group">
              <label>结束时间</label>
              <input type="datetime-local" id="endTime" name="endTime">
            </div>
            <div class="form-group">
              <label>日志类型</label>
              <select id="logType" name="logType">
                <option value="">全部</option>
                <option value="OPERATION">操作日志</option>
                <option value="SYSTEM">系统日志</option>
                <option value="SCHEDULE">调度日志</option>
                <option value="DEVICE">设备日志</option>
              </select>
            </div>
            <div class="form-group">
              <label>日志级别</label>
              <select id="level" name="level">
                <option value="">全部</option>
                <option value="DEBUG">DEBUG</option>
                <option value="INFO">INFO</option>
                <option value="WARN">WARN</option>
                <option value="ERROR">ERROR</option>
                <option value="FATAL">FATAL</option>
              </select>
            </div>
          </div>
          
          <div class="form-row">
            <div class="form-group">
              <label>模块</label>
              <input type="text" id="module" name="module" placeholder="输入模块名称">
            </div>
            <div class="form-group">
              <label>操作</label>
              <input type="text" id="action" name="action" placeholder="输入操作名称">
            </div>
            <div class="form-group">
              <label>用户ID</label>
              <input type="number" id="userId" name="userId" placeholder="输入用户ID">
            </div>
            <div class="form-group">
              <label>是否成功</label>
              <select id="success" name="success">
                <option value="">全部</option>
                <option value="true">成功</option>
                <option value="false">失败</option>
              </select>
            </div>
          </div>
          
          <div class="form-row">
            <div class="form-group">
              <label>关键词搜索</label>
              <input type="text" id="keyword" name="keyword" placeholder="输入搜索关键词">
            </div>
            <div class="form-group">
              <label>设备ID</label>
              <input type="text" id="deviceId" name="deviceId" placeholder="输入设备ID">
            </div>
            <div class="form-group">
              <label>机器人ID</label>
              <input type="text" id="robotId" name="robotId" placeholder="输入机器人ID">
            </div>
            <div class="form-group">
              <label>任务ID</label>
              <input type="text" id="taskId" name="taskId" placeholder="输入任务ID">
            </div>
          </div>
          
          <div class="form-actions">
            <button type="submit" class="primary">查询</button>
            <button type="button" class="secondary" onclick="resetQueryForm()">重置</button>
          </div>
        </form>
      </div>
      
      <!-- 日志列表 -->
      <div class="card">
        <div class="card-header">
          <h2 class="card-title">日志列表</h2>
          <div class="card-actions">
            <div class="pagination-info">
              共 <span id="totalCount">0</span> 条记录，每页 
              <select id="pageSize" onchange="onChangePageSize()">
                <option value="10">10</option>
                <option value="20">20</option>
                <option value="50">50</option>
                <option value="100">100</option>
              </select> 条
            </div>
          </div>
        </div>
        <div class="table-container">
          <table class="data-table">
            <thead>
              <tr>
                <th>ID</th>
                <th>时间</th>
                <th>类型</th>
                <th>级别</th>
                <th>模块</th>
                <th>操作</th>
                <th>用户ID</th>
                <th>状态</th>
                <th>消息</th>
                <th>关联ID</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody id="logsTableBody">
              <!-- 日志列表内容将通过JavaScript动态填充 -->
            </tbody>
          </table>
        </div>
        <!-- 分页控件 -->
        <div class="pagination">
          <button id="prevPage" onclick="onPrevPage()" disabled>上一页</button>
          <span id="paginationInfo">第 <span id="currentPage">1</span> 页</span>
          <button id="nextPage" onclick="onNextPage()" disabled>下一页</button>
        </div>
      </div>
      
      <!-- 日志详情模态框 -->
      <div id="logDetailModal" class="modal hidden">
        <div class="modal-content">
          <div class="modal-header">
            <h3>日志详情</h3>
            <button class="close-btn" onclick="closeLogDetailModal()">×</button>
          </div>
          <div class="modal-body">
            <pre id="logDetailContent"></pre>
          </div>
          <div class="modal-footer">
            <button onclick="closeLogDetailModal()">关闭</button>
          </div>
        </div>
      </div>
    </div>
  </div>

  <script src="js/utils.js?v=20250902"></script>
  <script src="js/admin.js?v=20250902"></script>
  <script src="js/logs.js?v=20250902"></script>
  <script>
    // 页面加载完成后执行
    document.addEventListener('DOMContentLoaded', function() {
      console.log('Admin dashboard loaded');
      
      // 初始化调试面板
      initDebugPanel();
      
      // 检查是否有保存的token
      let loadedToken = loadToken(); // 现在返回的是token值本身，而不是布尔值
      if (!loadedToken) {
        console.log('No token found in localStorage');
        // 检查URL参数中是否包含token
        const urlParams = new URLSearchParams(window.location.search);
        const urlToken = urlParams.get('token');
        if (urlToken) {
          console.log('Token found in URL parameter');
          // 保存URL中的token
          saveToken(urlToken);
          console.log('Token saved to localStorage from URL parameter');
          
          // 重新加载 token
          loadedToken = loadToken();
        } else {
          console.log('No token found in URL parameter, redirecting to login');
          // 没有token，重定向到登录页面
          window.location.href = 'login.html';
          return;
        }
      }
      
      console.log('Token value: ' + token);
      
      // 获取用户信息 - 添加更详细的错误处理
      request(api.me).then(resp => {
        // 检查响应状态，即使失败也尝试显示更多信息
        if (resp.ok && resp.data && resp.data.success && resp.data.data) {
          const user = resp.data.data;
          
          // 检查用户角色
          if (user.role !== 'ADMIN') {
            // 非管理员用户重定向到用户面板
            window.location.href = 'user-dashboard.html';
            return;
          }
          
          // 设置管理员信息
          document.getElementById('admin-name').textContent = user.name || user.username;
          document.getElementById('admin-role').textContent = user.role;
          
          // 加载管理员页面
          loadAdminPage();
        } else {
          // 显示更详细的错误信息
          
          // 只有在确实需要清除token的情况下才清除
          // 暂时注释掉clearToken和跳转，先查看问题
          // clearToken();
          // window.location.href = 'login.html';
        }
      }).catch(error => {
        // 清除token并重定向到登录页面
        clearToken();
        window.location.href = 'login.html';
      });
      
      // 为导航链接添加事件监听器
      document.querySelectorAll('.nav-link').forEach(link => {
        link.addEventListener('click', function(e) {
          e.preventDefault();
          const page = this.getAttribute('data-page');
          navigateTo(page);
        });
      });
    });
    
    // 编辑用户模态框相关函数
    function openEditUserModal(user) {
      document.getElementById('editUserId').value = user.userId || '';
      document.getElementById('editUserIdDisplay').value = user.userId || '';
      document.getElementById('editUsername').value = user.username || '';
      document.getElementById('editEmail').value = user.email || '';
      document.getElementById('editPhone').value = user.phone || '';
      document.getElementById('editName').value = user.name || '';
      document.getElementById('editIdCard').value = user.idCard || '';
      document.getElementById('editRole').value = user.role || 'USER';
      document.getElementById('editStatus').value = user.status || 'NORMAL';
      document.getElementById('editRemark').value = user.remark || '';
      
      // 只读字段
      const lastLoginTime = user.lastLoginTime ? new Date(user.lastLoginTime).toLocaleString() : 'N/A';
      document.getElementById('editLastLoginTime').value = lastLoginTime;
      document.getElementById('editCreator').value = user.creator || 'N/A';
      document.getElementById('editModifier').value = user.modifier || 'N/A';
      document.getElementById('editModifierHidden').value = user.modifier || '';
      
      document.getElementById('editUserModal').classList.remove('hidden');
    }
    
    function closeEditUserModal() {
      document.getElementById('editUserModal').classList.add('hidden');
    }
    
    // 重置密码模态框相关函数
    function openResetPasswordModal(user) {
      document.getElementById('resetUserId').value = user.userId || '';
      document.getElementById('resetUsername').textContent = user.username || '';
      document.getElementById('resetNewPassword').value = '';
      
      document.getElementById('resetPasswordModal').classList.remove('hidden');
    }
    
    function closeResetPasswordModal() {
      document.getElementById('resetPasswordModal').classList.add('hidden');
    }
  </script>
</body>
</html>